package com.server.orm;

import com.server.orm.db.table.TB_role;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.MemoryUnit;

import java.time.Duration;

/**
 * Ehcache3 缓存
 */
public class EhcacheManager {

    private static final EhcacheManager instance = new EhcacheManager();

    public static EhcacheManager getInstance() {
        return instance;
    }

    // 构建一个缓存管理器
    private CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);

    public void init() {

    }

    private void initCache() {
        ResourcePoolsBuilder resourcePoolsBuilder = ResourcePoolsBuilder.newResourcePoolsBuilder();
        resourcePoolsBuilder.heap(10, MemoryUnit.MB);//设置缓存堆容纳元素个数(JVM内存空间)超出个数后会存到offheap中
        resourcePoolsBuilder.offheap(10, MemoryUnit.MB);//设置堆外储存大小(内存存储) 超出offheap的大小会淘汰规则被淘汰
        resourcePoolsBuilder.disk(0, MemoryUnit.MB, false);// 配置磁盘持久化储存(硬盘存储)用来持久化到磁盘,这里设置为false不启用

        // 缓存淘汰策略 默认策略是LRU（最近最少使用）
        CacheConfiguration<String, String> cacheConfStringKey = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, resourcePoolsBuilder)
                .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(1)))// 存活时间，过期后自动清除
                .build();//最后调用build()返回一个完整的实例，但是该实例并未初始化。

        CacheConfiguration<Long, String> cacheConfLongKey = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, resourcePoolsBuilder)
                .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(1)))// 存活时间，过期后自动清除
                .build();//最后调用build()返回一个完整的实例，但是该实例并未初始化。

        Cache<Long, String> TB_role_cache = cacheManager.createCache(TB_role.class.getSimpleName(), cacheConfLongKey);
        Cache<String, String> TB_token_cache = cacheManager.createCache(TB_role.class.getSimpleName(), cacheConfStringKey);
    }

    public String getCacheV(Class k, Class V) {
        Cache<Long, String> cache = cacheManager.getCache(TB_role.class.getSimpleName(), k, V);
        return cache.get(1L);
    }

}
